package shoppingmall.common.utils;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 工具类-绘制验证码图片
 */
public class PictureCaptchaGenerator {

    private static final int WIDTH = 160;  //绘制图片宽度
    private static final int HEIGHT = 40;  //绘制图片高度
    private static final int CODE_COUNT = 4;  //绘制验证码位数
    private static final int LINE_COUNT = 5;  //绘制干扰线数量

    public static BufferedImage generateCaptchaImage(String captchaCode) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandomColor(200, 250));  //设置绘制图片矩形画笔颜色
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 30));
        g.setColor(getRandomColor(random.nextInt(255),random.nextInt(255)));  //设置绘制干扰线条画笔颜色
        for (int i = 0; i < LINE_COUNT; i++) {
            int x = random.nextInt(10); //线条起始x坐标[0-9)
            int y = random.nextInt(HEIGHT);  //线条起始y坐标[0-40)
            int xl = WIDTH -  random.nextInt(10);  //线条结束x坐标(160 - [0~9))
            int yl = random.nextInt(HEIGHT);  //线条结束y坐标[0-40)
            g.drawLine(x, y, xl, yl);
        }
        for (int i = 0; i < CODE_COUNT; i++) {
            String strRand = String.valueOf(captchaCode.charAt(i));
            //设置绘制数字验证码画笔颜色
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            //绘制验证码
            g.drawString(strRand, 30 * i + 20, 30);
        }
        g.dispose();
        return image;
    }

    /**
     * 随机获取颜色，用于设置画笔颜色
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandomColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        if((bc - fc) < 0) {
            bc = 255;
            fc = 100;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}


